local pre_path_input = "csv/"
local pre_path_output = "csv2ts/"

local function csv_to_ts(input_file, output_file, delimiter)
    delimiter = delimiter or ","
    local file = io.open(pre_path_input.. input_file, "r")
    if not file then
        error("无法打开CSV文件: " .. input_file)
    end

    local output = {"let config : {"}
    local headers = {}

    -- 跳过前3行注释
    for _ = 1, 3 do
        local comment_line = file:read("*l")
        -- if not comment_line then
        --     error("CSV文件格式不正确，缺少注释行")
        -- end
    end

    -- 读取表头
    local first_line = file:read("*l")
    if not first_line then
        error("CSV文件格式不正确，缺少表头行")
    end

    for header in first_line:gmatch("[^" .. delimiter .. "]+") do
        local trimmed_header = header:gsub("^%s*(.-)%s*$", "%1")
        table.insert(headers, trimmed_header)
        -- output[#output + 1] = "    -- " .. trimmed_header
    end

    if #headers == 0 then
        error("表头未正确读取")
    end

    -- 读取数据行
    for line in file:lines() do
        -- output[#output + 1] = "    {"
        local col = 1
        for value in line:gmatch("[^" .. delimiter .. "]+") do
            value = value:gsub("^%s*(.-)%s*$", "%1")
            if tonumber(value) then
                value = tonumber(value)
            elseif value == "true" then
                value = true
            elseif value == "false" then
                value = false
            else
                value = string.format("%q", value)
            end

            if col == 1 then
                output[#output + 1] = "    [" .. tostring(value) .. "] : {"
            end

            if headers[col] then
                output[#output + 1] = "        " .. headers[col] .. " : " .. tostring(value) .. ","
            else
                error("数据行列数与表头不匹配")
            end

            col = col + 1
        end

        output[#output] = output[#output]:gsub(",$", "")  -- 移除最后一个多余的逗号
        output[#output + 1] = "    },"
    end

    file:close()
    output[#output] = output[#output]:gsub(",$", "")  -- 移除最后一个多余的逗号
    output[#output + 1] = "}"

    -- 写入输出文件
    local out_file, err = io.open(pre_path_output .. output_file, "w")
    if not out_file then
        error("无法创建输出文件: " .. output_file .. " 错误信息: " .. err)
    end

    out_file:write(table.concat(output, "\n"))
    out_file:close()

    print("转换完成! 输出文件: " .. output_file)
end

-- 使用示例
print("请输入的文件名(不带后缀名):")
local line = io.read()
local input_file = line .. ".csv"
local output_file = line .. ".ts"
local delimiter = ","
print("csv: " .. input_file .. " ts: " .. output_file .. " delimiter: " .. delimiter)
csv_to_ts(input_file, output_file, delimiter)

